﻿using System;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.SharePoint.Explorer;
using CodeCounsel.SharePoint.DevTools.Commands;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;
using System.Windows.Forms;

namespace CodeCounsel.SharePoint.DevTools.ExplorerNodeExtensions
{
    [Export(typeof(IExplorerNodeTypeProvider)),
    ExplorerNodeType(NodeIDs.FieldNode)]
    public class FieldNodeTypeProvider
        : IExplorerNodeTypeProvider
    {
        internal static void CreateFieldNodes(IExplorerNode parentNode)
        {
             FieldInfo[] fields = parentNode.Context.SharePointConnection.ExecuteCommand<FieldInfo[]>(CommandIDs.GetFields);
             foreach (FieldInfo field in fields)
             {
                 CreateNode(parentNode, field);
             }
        }

        internal static IExplorerNode CreateNode(IExplorerNode parentNode, FieldInfo field)
        {
            Dictionary<object, object> annotations = new Dictionary<object, object>();
            annotations.Add(typeof(FieldInfo), field);
            return parentNode.ChildNodes.Add(NodeIDs.FieldNode, field.Name, annotations);
        }

        public void InitializeType(IExplorerNodeTypeDefinition typeDefinition)
        {
            typeDefinition.IsAlwaysLeaf = true;
            typeDefinition.NodePropertiesRequested += NodePropertiesRequested;
            typeDefinition.NodeMenuItemsRequested += new EventHandler<ExplorerNodeMenuItemsRequestedEventArgs>(NodeMenuItemsRequested);
        }

        void NodePropertiesRequested(object sender, ExplorerNodePropertiesRequestedEventArgs e)
        {
            FieldInfo fieldInfo = e.Node.GetAnnotation<FieldInfo >();
            Dictionary<string, string> fieldProperties = e.Node.Context.SharePointConnection.ExecuteCommand<FieldInfo, Dictionary<string, string>>(CommandIDs.GetFieldProperties, fieldInfo);
            object propertySource = e.Node.Context.CreatePropertySourceObject(fieldProperties);
            e.PropertySources.Add(propertySource);
        }

        void NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            IMenuItem copyIDMenuItem = e.MenuItems.Add("Copy ID");
            copyIDMenuItem.Click +=
                delegate
                {
                    FieldInfo nodeInfo = e.Node.GetAnnotation<FieldInfo>();
                    Clipboard.SetData(DataFormats.Text, nodeInfo.ID.ToString("B"));
                };

        }
    }
}
